package com.project.harmonyledger.service.impl.user.account;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.project.harmonyledger.common.response.Result;
import com.project.harmonyledger.common.response.ResultCode;
import com.project.harmonyledger.mapper.UserMapper;
import com.project.harmonyledger.pojo.User;
import com.project.harmonyledger.service.user.account.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class RegisterServiceImpl implements RegisterService {
  @Autowired
  private UserMapper userMapper;

  @Autowired
  private PasswordEncoder passwordEncoder;

  @Override
  public Result<Map<String, String>> register(String username, String password, String confirmedPassword) {
    Map<String, String> map = new HashMap<>();

    ResultCode validationResult = validateRegistration(username, password, confirmedPassword);
    if (validationResult != ResultCode.SUCCESS) {
      map.put("message", validationResult.getMessage());
      return Result.error(validationResult, map);
    }

    // 检查用户名是否已存在
    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("username", username);
    List<User> users = userMapper.selectList(queryWrapper);
    if (!users.isEmpty()) {
      map.put("message", ResultCode.USER_EXISTS.getMessage());
      return Result.error(ResultCode.USER_EXISTS, map);
    }

    // 创建新用户
    String encodedPassword = passwordEncoder.encode(password);
    String nickname = "新人用户";
    String photo = "https://cdn.acwing.com/media/user/profile/photo/29231_lg_3e166b549d.jpg";
    User user = new User(username, encodedPassword, nickname, photo);
    userMapper.insert(user);

    map.put("message", ResultCode.SUCCESS.getMessage());
    return Result.success(map);
  }

  private ResultCode validateRegistration(String username, String password, String confirmedPassword) {
    if (username == null || username.trim().isEmpty()) {
      return ResultCode.USERNAME_EMPTY;
    }
    if (password == null || confirmedPassword == null ||
        password.isEmpty() || confirmedPassword.isEmpty()) {
      return ResultCode.PASSWORD_EMPTY;
    }

    username = username.trim();
    if (username.length() > 100) {
      return ResultCode.BAD_REQUEST;
    }
    if (password.length() > 100 || confirmedPassword.length() > 100) {
      return ResultCode.BAD_REQUEST;
    }
    if (!password.equals(confirmedPassword)) {
      return ResultCode.PASSWORD_NOT_MATCH;
    }

    return ResultCode.SUCCESS;
  }
}
